package com.huangpuweb.task.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.huangpuweb.task.Constants;
import com.huangpuweb.task.model.SysHpScenicState;
import com.huangpuweb.task.model.SysRefinedCrowdSituation;
import com.huangpuweb.task.service.SyncQzYYGFDataService;
import com.huangpuweb.task.service.SyncSysDataService;
import com.huangpuweb.task.util.DateUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.codec.Charsets;
import org.apache.commons.logging.LogFactory;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.util.EntityUtils;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;

import java.io.IOException;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.UUID;


/**
 * 同步阿里提供的南京路步行街客流数据
 */
@Controller
public class SyncDataFromAlibabaJob {

    private static Logger logger = Logger.getLogger(SyncDataFromAlibabaJob.class);


    private SyncQzYYGFDataService syncQzYYGFDataService;

    @Autowired
    public void setSyncQzYYGFDataService(SyncQzYYGFDataService syncQzYYGFDataService) {
        this.syncQzYYGFDataService = syncQzYYGFDataService;
    }

    private SyncSysDataService syncSysDataService;

    @Autowired
    public void setSyncSysDataService(SyncSysDataService syncSysDataService) {
        this.syncSysDataService = syncSysDataService;
    }


    /**
     * 定时同步阿里南京路点位数据-热力图使用
     */
    public void SyncDataFromAlibabaPersonCountTask() throws Exception {

        String content ="";
        LogFactory.getLog(this.getClass()).info("------SyncDataFromAlibabaPersonCountTask-----start-------");
        try {
            //http://215.0.0.31:8085/person/all?region=njdl
            String url = "http://215.0.0.31:8085/person/all/njdl";
            HttpClient httpClient = new DefaultHttpClient();
            HttpGet get=new HttpGet(url);
            HttpResponse response = httpClient.execute(get);
            content=EntityUtils.toString(response.getEntity());
        } catch (IOException e) {
            e.printStackTrace();
        }
        syncSysDataService.insertAlibabaPersonCount(content,"njdl");
    }
    /**
     * 定时同步阿里外滩点位数据-热力图使用
     */
    public void SyncDataFromAlibabaWt() throws Exception {

        String content ="";
        LogFactory.getLog(this.getClass()).info("------SyncDataFromAlibabaWt-----start-------");
        try {
            String url = "http://215.0.0.31:8085/person/all/wt";
            HttpClient httpClient = new DefaultHttpClient();
            HttpGet get=new HttpGet(url);
            HttpResponse response = httpClient.execute(get);
            content=EntityUtils.toString(response.getEntity());
        } catch (IOException e) {
            e.printStackTrace();
        }
        syncSysDataService.insertAlibabaWt(content,"wt");
    }
    public void updateThreeDataTask(){
        LogFactory.getLog(this.getClass()).info("------updateThreeDataTask-----start-------");
        syncSysDataService.updateThreeData();

    }


    /**
     * 阿里路东拓
     * http://215.0.0.31:8086/person/camera?id=31010112001328035012
     */
    public void SyncDataFromAlibabaPersonDongTuoCountTask() throws Exception {
        String content ="";
        LogFactory.getLog(this.getClass()).info("------SyncDataFromAlibabaPersonDongTuoCountTask-----start-------");
//        System.out.println("--------start-------SyncDataFromAlibabaPersonDongTuoCountTask----------" + new Date());
//        List<String> carmalist=new ArrayList<String>();
//        carmalist.add("31010111001180006013");
//        carmalist.add("31010113001180026005");
//        carmalist.add("31010113001180026006");
//        carmalist.add("31010113001180026008");
//        carmalist.add("31010113001180026009");
//        carmalist.add("31010113001180026012");
//        carmalist.add("31010113001180026016");
//        carmalist.add("31010113001180030001");
//        carmalist.add("31010111001180004020");
//        carmalist.add("31010113001180030009");
//        carmalist.add("31010113001180027007");
//        carmalist.add("31010113001180027012");
//        carmalist.add("31010113001180030016");
//        carmalist.add("31010111001180003010");
//        carmalist.add("31010113001180031008");
//        carmalist.add("31010113001180028004");
//        carmalist.add("31010113001180028016");
//        carmalist.add("31010113001180029007");
//        carmalist.add("31010113001180029010");
        Integer sum=0;
        try {
        String url = "http://215.0.0.31:8085/stat/global_estimate/area/njdldtd";
                HttpClient httpClient = new DefaultHttpClient();
                HttpGet get=new HttpGet(url);
                HttpResponse response = httpClient.execute(get);
                // 判断是否正常返回
                if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
                    // 解析数据
                    String data = EntityUtils.toString(response.getEntity(), Charsets.UTF_8).replaceAll("\\\n","");
                    sum=Integer.valueOf(data);
                }

            } catch (IOException e) {
                sum=sum+0;
            }
//        for(String carmeid:carmalist){
//            try {
//                //31010111001180006013
//                String url = "http://215.0.0.31:8086/person/camera?id="+carmeid;
//                HttpClient httpClient = new DefaultHttpClient();
//                HttpGet get=new HttpGet(url);
//                HttpResponse response = httpClient.execute(get);
//                // 判断是否正常返回
//                if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
//                    // 解析数据
//                    String data = EntityUtils.toString(response.getEntity(), Charsets.UTF_8);
//                    JSONObject jo = JSONObject.parseObject(data);
//                    Integer length=jo.getJSONArray("gps").size();
//                    sum=sum+length;
//                }
//
//
//            } catch (IOException e) {
//                sum=sum+0;
//            }
//        }

        SysRefinedCrowdSituation sysrefinedcrowd = new SysRefinedCrowdSituation();
        sysrefinedcrowd.setId(UUID.randomUUID().toString().replaceAll("-", ""));
        //设置数据创建时间
        sysrefinedcrowd.setCreateTime(DateUtil.getDateTime());
        //设置数据更新时间
        sysrefinedcrowd.setUpdateTime(DateUtil.getDateTime());
        //设置景区名称
        sysrefinedcrowd.setSpotName(Constants.NANJINGLUNAMEDONGTUO);
        //设置景区编码
        sysrefinedcrowd.setSpotCode(Constants.NANJINGLUDONGTUOCODE);
        //设置实时人流
        sysrefinedcrowd.setRealtimeNumber(sum);
        //设置累计宗人流量
        sysrefinedcrowd.setTotalNumber(0);
        //设置数据来源
        sysrefinedcrowd.setDataSources("阿里");
        //设置对接方式
        sysrefinedcrowd.setRemarks("接口对接");
        //插入数据
        syncSysDataService.insertSysRefinedCrowdSituation(sysrefinedcrowd);
        //插入数据到备份表中
        syncSysDataService.insertSysBackupCrowdSituation(sysrefinedcrowd);
    }




    /**
     * 定时同步豫园股份数据
     *
     * @throws Exception
     */
    public void SyncDataFromAlibabaJobTask() throws Exception {


        LogFactory.getLog(this.getClass()).info("--------start-------SyncDataFromAlibabaJobTask----------" + new Date());
        //System.out.println("--------start-------SyncDataFromAlibabaJobTask----------" + new Date());


        /**
         * 同步豫园股份数据到Sys_refined_crowdSituation表
         */
        logger.info("更新南京路实时数据开始");
        syncDataFromALIBABA();
        logger.info("更新南京路实时数据结束");
        /**
         * 清洗数据到_state表中
         */
        saveScenicStateData();

        LogFactory.getLog(this.getClass()).info("--------end-------SyncDataFromAlibabaJobTask----------" + new Date());


    }

    /**
     * 开始同步阿里南京路数据
     */
    private void syncDataFromALIBABA() {

        int sum = 0;

        try {
            // 创建HttpClient实例
            HttpClient client = HttpClientBuilder.create().build();
            // 根据URL创建HttpGet实例
            HttpGet get = new HttpGet(Constants.ALIBABAURL);
            // 执行get请求，得到返回体
            HttpResponse response = client.execute(get);
            // 判断是否正常返回
            if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
                // 解析数据
                String data = EntityUtils.toString(response.getEntity(), Charsets.UTF_8);
                sum=Integer.valueOf(data.trim());
//                JSONObject jo = JSONObject.parseObject(data);
//                sum = Integer.valueOf(jo.getString("sum").trim());
//                int code = Integer.valueOf(jo.getString("code"));
////                if (code == 0) {
////                    sum = Integer.valueOf(jo.getString("sum").trim());
////                } else {
////                    LogFactory.getLog(this.getClass()).info("--------error-------SyncDataFromAlibabaInterface----------" + new Date());
////                }
                SysRefinedCrowdSituation sysrefinedcrowd = new SysRefinedCrowdSituation();
                sysrefinedcrowd.setId(UUID.randomUUID().toString().replaceAll("-", ""));
                //设置数据创建时间
                sysrefinedcrowd.setCreateTime(DateUtil.getDateTime());
                //设置数据更新时间
                sysrefinedcrowd.setUpdateTime(DateUtil.getDateTime());
                //设置景区名称
                sysrefinedcrowd.setSpotName(Constants.NANJINGLUNAME);
                //设置景区编码
                sysrefinedcrowd.setSpotCode(Constants.NANJINGLUCODE);
                //设置实时人流
                sysrefinedcrowd.setRealtimeNumber(sum);
                //设置累计宗人流量
                sysrefinedcrowd.setTotalNumber(0);
                //设置数据来源
                sysrefinedcrowd.setDataSources("阿里");
                //设置对接方式
                sysrefinedcrowd.setRemarks("接口对接");
                //插入数据
                syncSysDataService.insertSysRefinedCrowdSituation(sysrefinedcrowd);
                //插入数据到备份表中
                syncSysDataService.insertSysBackupCrowdSituation(sysrefinedcrowd);


            }
        } catch (Exception e) {
            LogFactory.getLog(this.getClass()).info("--------error-------SyncDataFromAlibabaJobTask----------" + new Date());
        }
    }
public   void keLiuShuSan(){
    int sum =syncSysDataService.selectOne();
    String content;
    JSONObject jsonObject=null;
try {
    logger.info("keLiuShuSan-----start");
    String url = "http://215.0.0.31:8085/evacuation?flows_in=500&people_num="+String.valueOf(sum);
    HttpClient httpClient = new DefaultHttpClient();
    HttpGet get = new HttpGet(url);
    HttpResponse response = httpClient.execute(get);
    content = EntityUtils.toString(response.getEntity());
    jsonObject = JSON.parseObject(content);
    String t_4k = jsonObject.getString("t_4k");
    String t_10k = jsonObject.getString("t_10k");
    String t_20k = jsonObject.getString("t_20k");
    String flows = jsonObject.getString("flows");
    syncSysDataService.insertKeLiuShuSan(t_4k,t_10k,t_20k,flows,sum);
}catch (Exception e){
    logger.error("keLiuShuSan-----error"+e);
}
}

    private void saveScenicStateData() {

        //  String[] spotCodeArr = Constants.SPOTCODELIST.split(",");

        //获取当前日期的0点和23点
        String todayZero = DateUtil.getTodayZero();
        String today23 = DateUtil.getToday23(23, 59, 59);


        //获取截至目前人流量峰值和时间,景区名称、景区编号
        SysRefinedCrowdSituation maxSysrefinedcrowd = syncSysDataService.getMaxNumberBySysRefinedCrowdSituation("SHHPQ_NANJINGLU", todayZero, today23);

        //获取最新的实施人流量和今日总人流量
        SysRefinedCrowdSituation realSysrefinedcrowd = syncSysDataService.getRealNumberBySysRefinedCrowdSituation("SHHPQ_NANJINGLU");

        SysHpScenicState sysHpScenicState = new SysHpScenicState();

        if (maxSysrefinedcrowd != null && realSysrefinedcrowd != null) {
            //设置景区名称
            sysHpScenicState.setSpotName(maxSysrefinedcrowd.getSpotName());
            //设置景区编码
            sysHpScenicState.setSpotCode("SHHPQ_NANJINGLU");
            //设置景区今日峰值
            sysHpScenicState.setMaxNumber(maxSysrefinedcrowd.getRealtimeNumber());
            //设置景区峰值产生时间
            sysHpScenicState.setMaxTime(maxSysrefinedcrowd.getCreateTime());
            //设置景区实时人流量
            int realtimeNumber = Integer.valueOf(realSysrefinedcrowd.getRealtimeNumber());
            sysHpScenicState.setRealTimeNumber(realtimeNumber);
            //设置景区总人流量
            sysHpScenicState.setTotalNumber(Integer.valueOf(realSysrefinedcrowd.getTotalNumber()));
            //设置景区面积 SPOTCODELIST
            String area = "2";
            sysHpScenicState.setSpotArea(area);
            //设置人群密度
            DecimalFormat df = new DecimalFormat("0.00");
            double _area = Double.valueOf(area) * 10000;
            String density = df.format(realtimeNumber / _area);
            sysHpScenicState.setPeopleDensity(density);
            //设置景区监控点
            //TODO
            //获取景区摄像头数量
            String spotmonitornumber = "0";


            int monitorNumber = 0;
            if (null != spotmonitornumber) {
                monitorNumber = Integer.valueOf(spotmonitornumber);
            }
            sysHpScenicState.setMonitorNumber(monitorNumber);
            //设置风险等级
            sysHpScenicState.setRiskLevel(realtimeNumber);
            sysHpScenicState.setRecordTime(DateUtil.getDateTime());
            //更新数据 hp_scenic_state
            syncSysDataService.updateHpScenicState(sysHpScenicState);
        }


    }


}
